import pandas as pd
import os
import logging
from pathlib import Path

logging.basicConfig(level=logging.WARNING)  # 修改为WARNING级别
logger = logging.getLogger(__name__)


def convert_to_md(input_path, output_folder):
    try:
        logger.info(f"开始处理Excel文件: {input_path}")
        Path(output_folder).mkdir(parents=True, exist_ok=True)
        filename = os.path.basename(input_path)
        name, ext = os.path.splitext(filename)
        output_path = os.path.join(output_folder, f"{name}.md")

        # 读取Excel文件
        logger.info("读取Excel文件内容...")
        df = pd.read_excel(input_path)
        
        logger.info("将Excel内容转换为Markdown格式...")
        md_content = df.to_markdown(index=False, tablefmt="github")

        # 写入文件
        logger.info(f"将Markdown内容写入文件: {output_path}")
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(md_content)

        logger.info(f"Excel文件成功转换为Markdown: {output_path}")
        return output_path
    except Exception as e:
        logger.error(f"Excel转Markdown失败: {str(e)}")
        raise
